package com.zuoshenge.sys.controller;

import com.zuoshenge.sys.entity.User;
import com.zuoshenge.sys.service.GameService;
import com.zuoshenge.sys.service.OnlineUserService;
import com.zuoshenge.sys.service.UserDataService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("game")
public class GameController {

    @Resource
    private UserDataService userDataService;

    @Resource
    private GameService gameService;

    @Resource
    private OnlineUserService onlineUserService;

    @GetMapping("click")
    public ResponseEntity<Object> click(@RequestParam("username") String username) {
        long timestamp = System.currentTimeMillis();
        long last = timestamp / 1000L * 1000L;
        long future = last + 1000L;
        User user = userDataService.loadUserByUsername(username);
        if (user == null) {
            throw new NullPointerException("user为空！");
        }
        Map<String, Object> result = new HashMap<>(2);
        Long punishmentTtl = onlineUserService.getPunishmentTtl(user.getUsername());

        if (punishmentTtl >= 0) {
            // 正在罚时
            result.put("result", -2);
            result.put("punishmentTtl", punishmentTtl);
            return ResponseEntity.ok(result);
        }

        if (user.getFreeCount() + user.getExtraCount() <= 0) {
            // 次数不足
            result.put("result", -1);
            return ResponseEntity.ok(result);
        } else {
            // 消耗次数
            if (user.getFreeCount() > 0) {
                gameService.reduceFree(username, 1);
            } else {
                gameService.reduceExtra(username, 1);
            }
        }

        if (timestamp > last + 100L && timestamp < future - 100L ) {
            // 没抽中
            result.put("result", 0);
        } else if (timestamp <= last + 100L) {
            // 奖励积分 + 添加中奖记录
            userDataService.handleClick(user, 1);
            result.put("result", 1);
        } else if (timestamp >= future - 100L) {
            // 罚时
            userDataService.punishment(user);
            result.put("result", 2);
        }
        // 再查询一遍用户的最新的信息
        // TODO 解决多次并发修改后，如何保证回传的数据具有准确性
        result.put("user", userDataService.loadUserByUsername(username));
        return ResponseEntity.ok(result);
    }

    @GetMapping("/test")
    public void test() {
        System.out.println("ok");
    }
}
